package com.dyz.leetcode._08_StackAndQueue;

import java.util.*;

public class _151_reverseWords {
    //使用API
    public String reverseWords1(String s) {
        s = s.trim();
        List<String> list = Arrays.asList(s.split("\\s+"));
        Collections.reverse(list);
        return String.join(" ", list);
    }
    //双端队列
    public String reverseWords(String s) {
         /*
        输入：s = "  Bob    Loves  Alice   "
        1. "Bob    Loves  Alice"
        2.
          -----------------------------
                Alice Loves Bob
          ----------------------------

        输出："Alice Loves Bob"
         */
        int left = 0, right = s.length() - 1;
        // 去掉开头的空格
        while (left <= right && s.charAt(left) == ' '){ left++;}
        // 去掉结尾的空格
        while (left <= right && s.charAt(right) == ' '){ right--;}
        Deque<String> deque = new ArrayDeque<>();
        StringBuilder word = new StringBuilder();
        while (left<=right){
            char c = s.charAt(left);
            if(c!=' '){
                word.append(c);
            }else if(word.length()!=0){
                deque.offerFirst(word.toString());
                word.setLength(0);
            }
            left++;
        }
        deque.offerFirst(word.toString());
        return String.join(" ", deque);
    }
}
